<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import Swipers from '@/pages/goodsDetails/swipers.vue';
import Shops from '@/pages/goodsDetails/shops.vue';
import { goodsDetailGet } from '@/services/goods.ts';
import whitecar from '@/assets/icons/whitecar.svg';
import home from '@/assets/icons/home.svg';
import type { GoodsList, FieldConfig } from '@/types/index.ts';

const $route = useRoute();
const $router = useRouter();
watch(
  () => $route.params,
  () => {
    loadData();
  },
);
const isImage = computed(() => {
  let reg = /(\.jpg|\.jpeg|\.png)$/i;
  return reg.test(goodsList.value.goodsIntro?.productFormation || '');
});
const goodsList = ref<Partial<GoodsList>>({
  goodsId: '',
  goodsImg: '',
  goodsSalesPrice: '',
  goodsSubtitle: '',
  goodsName: '',
  supplierName: '',
  afterPhone: '',
  isCombo: '',
  goodsExpandparamValueList: [],
  apparatusCategory: {
    apparatusCategoryName: '',
    apparatusCategoryLevel: '',
  },
  goodsIntro: {},
  instructions: [],
  goodsDetailImg: [],
  goodsQualificationList: [],
});
const otherGoodsList = ref<GoodsList[]>([]);
const getCategoryText = (level: any) => {
  if (!goodsList.value.apparatusCategory) return '';
  const prefix = level === 1 ? '' : level === 2 ? 'II类医疗器械 / ' : 'III类医疗器械 / ';
  return `${prefix}${goodsList.value.apparatusCategory.apparatusCategoryName}`;
};

const carPop = ref(false);
const joinCarData = ref({});
const buttonType = ref(0);
const onJoinCarClick = (props: number) => {
  buttonType.value = props;
  joinCarData.value = goodsList.value;
  carPop.value = true;
};

const onActionBarClick = () => {
  $router.push({
    path: '/store',
    query: {
      supplierId: goodsList.value.supplierId,
    },
  });
};

const loadData = async () => {
  const { err, data } = await goodsDetailGet($route.params.id);
  if (err) {
    showToast(err);
    return;
  }
  otherGoodsList.value = data.otherGoods;
  goodsList.value = data.goodsVo;
  goodsList.value.instructions = JSON.parse(data.goodsVo.instructions);
  goodsList.value.goodsDetailImg = JSON.parse(data.goodsVo.goodsDetail);
};
const previewShow = ref(false);
const previewImages = ref<string[]>([]);
const onImageClick = (props: any) => {
  previewImages.value = [props];
  previewShow.value = true;
};
const fieldConfigs: FieldConfig[] = [
  { label: '生产企业', prop: 'productionEnterprise' },
  { label: '注册人', prop: 'registrant' },
  { label: '注册证号', prop: 'registrationNumber' },
  { label: '有效期（月）', prop: 'validityPeriod' },
  { label: '使用方法', prop: 'methodApplication' },
  { label: '适用范围', prop: 'applicationScope' },
  { label: '禁忌症', prop: 'contraindication' },
  { label: '产品组成', prop: 'productFormation' },
];
onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="goods_container">
    <Swipers :images="goodsList.goodsImg"></Swipers>
    <div class="goods_price">
      <div class="price">
        <span>￥</span>
        <span class="price_number">{{ goodsList.goodsSalesPrice }}</span>
      </div>
      <div class="goods_name">
        <van-text-ellipsis :content="`${goodsList.goodsName}`" />
      </div>
      <div class="goods_specs">
        <van-text-ellipsis :content="`${goodsList.goodsSubtitle}`" />
      </div>
    </div>
    <div class="product">
      <div class="product_title">
        {{ goodsList.isCombo === 'NO' ? '产品信息' : '套装包含以下商品(点击商品查看详情)' }}
      </div>
      <div class="product-box" v-if="goodsList.isCombo === 'NO'">
        <van-cell>
          <template #title>
            <span>器械类别</span>
          </template>
          <template #value>
            <span>{{ getCategoryText(goodsList.apparatusCategory?.apparatusCategoryLevel) }}</span>
          </template>
        </van-cell>
        <van-cell class="product_text" v-for="(field, index) in fieldConfigs" :key="index">
          <template #title>
            <span>{{ field.label }}</span>
          </template>
          <template #value>
            <van-image
              v-if="field.prop === 'productFormation' && isImage"
              :src="goodsList.goodsIntro?.[field.prop]"
              @click="onImageClick(goodsList.goodsIntro?.[field.prop])"
            ></van-image>
            <span v-else>{{ goodsList.goodsIntro?.[field.prop] }}</span>
          </template>
        </van-cell>
      </div>
      <div v-else class="comboStyle">
        <div v-for="(item, index) in goodsList.comboItemList" :key="index" class="combo-box">
          <div class="box-left">
            <van-text-ellipsis
              @click="$router.push(`/goodsDetails/${item.goodsId}`)"
              rows="1"
              :content="item.goodsName"
            />
          </div>
          <div class="box-right">{{ `x${item.num}` }}</div>
        </div>
      </div>
    </div>
    <Shops
      :goodsList="otherGoodsList"
      :shopName="goodsList.supplierName"
      :afterPhone="goodsList.afterPhone"
      :supplierId="goodsList.supplierId"
    ></Shops>
    <div class="product" style="margin-top: 4px">
      <div class="product_title">商品详情</div>
      <div v-if="(goodsList?.instructions || []).length > 0">
        <van-image
          @click="onImageClick(item)"
          v-for="(item, index) in goodsList?.instructions"
          :key="index"
          :src="item"
        >
          <template v-slot:loading>
            <van-loading type="spinner" size="20" />
          </template>
          <template v-slot:error>加载失败</template>
        </van-image>
      </div>
      <div v-if="(goodsList?.goodsDetailImg || []).length > 0">
        <van-image
          @click="onImageClick(item)"
          v-for="(item, index) in goodsList?.goodsDetailImg"
          :key="index"
          :src="item"
        >
          <template v-slot:loading>
            <van-loading type="spinner" size="20" />
          </template>
          <template v-slot:error>加载失败</template>
        </van-image>
      </div>
      <div v-if="(goodsList?.goodsQualificationList || []).length > 0">
        <div v-for="item in goodsList.goodsQualificationList" :key="item.id">
          <van-image
            @click="onImageClick(img)"
            v-for="(img, index) in item.qualificationImg.split(',')"
            :key="index"
            :src="img"
          >
            <template v-slot:loading>
              <van-loading type="spinner" size="20" />
            </template>
            <template v-slot:error>加载失败</template>
          </van-image>
        </div>
      </div>
      <div v-if="goodsList.goodsDetailImg?.length == 0 && goodsList.instructions?.length == 0">
        <van-empty description="暂无数据" />
      </div>
    </div>
  </div>
  <van-action-bar placeholder>
    <van-action-bar-icon to="/" :icon="home" text="首页" />
    <van-action-bar-icon @click="onActionBarClick" :icon="whitecar" text="店铺" />
    <van-action-bar-button @click="onJoinCarClick(2)" color="#00BA9F" text="加入购物车" />
    <van-action-bar-button @click="onJoinCarClick(3)" color="#E89000" text="立即购买" />
  </van-action-bar>
  <van-image-preview v-model:show="previewShow" :images="previewImages"></van-image-preview>
  <JoinCar v-model="carPop" :joinCarData="joinCarData" :buttonType="buttonType"></JoinCar>
</template>

<style scoped lang="scss">
.goods_container {
  width: 100%;
  background: #f6f6f6;

  .goods_price {
    width: 100%;
    height: 90px;
    padding: 8px 16px;
    margin-bottom: 4px;
    color: #e86600;
    background: white;

    .price {
      font-size: 14px;
      font-weight: 500;
      line-height: 28px;

      .price_number {
        font-size: 20px;
      }
    }

    .goods_name {
      font-size: 15px;
      font-weight: 600;
      color: #000000;
      line-height: 22px;
    }

    .goods_specs {
      font-size: 12px;
      font-weight: 400;
      line-height: 18px;
    }
  }

  .product {
    width: 100%;
    background: #f6f6f6;
    margin: 4px 0;

    .product_title {
      width: 100%;
      height: 42px;
      font-size: 15px;
      color: #000000;
      font-weight: 600;
      padding: 0 16px;
      line-height: 42px;
      background: white;
    }

    .product_text {
      .van-image {
        width: 88px;
        height: 88px;
        border-radius: 8px;
      }
    }

    .product-box {
      :deep(.van-cell__value) {
        font-size: 12px;
        padding-left: 16px;
        font-weight: 400;
        text-align: left;
        color: #222222;
      }
    }

    .comboStyle {
      width: 100%;
      padding: 0 16px;
      background: white;

      .combo-box {
        width: 100%;
        height: 44px;
        font-size: 12px;
        font-weight: 400;
        border-bottom: 1px solid #f6f6f6;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .box-left {
          color: #0486fe;
          width: 285px;
        }
      }
    }
  }
}

:deep(.van-cell__title) {
  min-width: 88px;
  max-width: 88px;
  color: #787878;
  font-size: 12px;
  font-weight: 400;
}

:deep(.van-cell__value) {
  font-size: 12px;
  font-weight: 400;
  text-align: left;
  color: #222222;
}
</style>
